package com.zzq.service.impl;



import com.aliyuncs.exceptions.ClientException;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzq.config.wx.WxJsapiConfig;
import com.zzq.domain.bo.SmileFeeBO;
import com.zzq.domain.dto.*;
import com.zzq.domain.entity.*;
import com.zzq.domain.search.AlbumSearchParamet;
import com.zzq.domain.search.PhotoSearchParamet;
import com.zzq.domain.search.ShootRecordSearchParament;
import com.zzq.domain.vo.SmilePhotoDownloadVO;
import com.zzq.enumerate.CouponStatusEnum;
import com.zzq.enumerate.DividendTypeEnum;
import com.zzq.enumerate.IncomeExpenditureStatusEnum;
import com.zzq.result.SmileResult;
import com.zzq.security.util.UserUtil;
import com.zzq.service.*;
import com.zzq.subservice.CostcalculcationSubService;
import com.zzq.subservice.EarnPointsSubService;
import com.zzq.util.BeanCopyUtils;
import com.zzq.util.ObjectUtils;
import com.zzq.util.OssFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class ClientAlbumServiceImpl implements ClientAlbumService {

    @Autowired
    SmileAlbumService albumService;

    @Autowired
    SmileShootAddressService shootAddressService;
    @Autowired
    SmileAlbumPhotoService albumPhotoService;

    @Autowired
    SmileClientService clientService;

    @Autowired
    SmileShootRecordService recordService;

    @Autowired
    SmilePhotographerService photographerService;

    @Autowired
    SmilePhotoService photoService;

    @Autowired
    SmilePhotographerDividendService dividendService;

    @Autowired
    SmilePhotographerDividendBillService dividendBillService;

    @Autowired
    SmilePhotographerDividendRuleService dividendRuleService;

    @Autowired
    SmileCouponService couponService;

    @Autowired
    OssFileUtil ossFileUtil;

    @Autowired
    CostcalculcationSubService costcalculcationUtil;

    @Autowired
    EarnPointsSubService earnPointsSubService;

    @Value("${wx.pay.jsapiurl}")
    private String jsapiurl;
    private WxJsapiConfig wxJsapiConfig;


    @Autowired
    public ClientAlbumServiceImpl(WxJsapiConfig wxJsapiConfig) {
        this.wxJsapiConfig = wxJsapiConfig;
    }
    @Override
    public SmileResult getAlbumList(AlbumSearchParamet searchParamet) {
        List<SmileAlbumDTO> smileAlbumDTOS = albumService.albumDTOList(searchParamet);
        return SmileResult.sucess("相册集合获取成功", smileAlbumDTOS);
    }

    //获取已解锁相册
    @Override
    public SmileResult getdownLoadAlbumListById(AlbumSearchParamet searchParamet) throws ClientException {
        searchParamet.setDownloadLock(true);
        List<SmileAlbumDTO> smileAlbumDTOS = albumService.albumDTOList(searchParamet);
        if (smileAlbumDTOS.size()!=1){
            return SmileResult.waring("解锁的当前相册获取有误");
        }
        SmileAlbumDTO smileAlbumDTO = smileAlbumDTOS.get(0);
        List<SmilePhotoDTO> smilePhotoDTOS = smileAlbumDTO.getSmilePhotoDTOS();
        for (SmilePhotoDTO smilePhotoDTO : smilePhotoDTOS) {
            String photoMetuDir = smilePhotoDTO.getPhotoMetuDir();
            String fileUrl = ossFileUtil.getFileUrl(photoMetuDir);
            log.info("相册路径：{}",fileUrl);
            smilePhotoDTO.setPhotoMetuUrl(fileUrl);
        }
        return SmileResult.sucess("解锁的当前相册获取成功",smileAlbumDTO);
    }

    /**
     * 结算金额
     * @param photoSearchParamet
     * @return
     */
    @Override
    public SmileResult settleAccounts(ShootRecordSearchParament photoSearchParamet) {
        SmileFeeBO smileFeeBo = costcalculcationUtil.getAmountSmileFeeDTO(photoSearchParamet);
        return SmileResult.sucess("计算成功", smileFeeBo);
    }

    @Override
    public SmileResult downLoad(PhotoSearchParamet photoSearchParamet) {
        try {
            Long userID = UserUtil.getUserID();
            SmileClient client = clientService.getById(userID);
            String clientNo = client.getClientNo();
            photoSearchParamet.setClientNo(clientNo);
            photoSearchParamet.setLockStatus(true);
            List<SmilePhotoDTO> smilePhotoDTOs = photoService.getDownloadDTO(photoSearchParamet);
            for (SmilePhotoDTO smilePhotoDTO : smilePhotoDTOs) {
                String photoMetuDir = smilePhotoDTO.getPhotoMetuDir();
                String fileUrl  = ossFileUtil.getFileUrl(photoMetuDir);
                smilePhotoDTO.setPhotoMetuUrl(fileUrl);
            }
            List<SmilePhotoDownloadVO> smilePhotoDownloadVOS = BeanCopyUtils.copyBeanList(smilePhotoDTOs, SmilePhotoDownloadVO.class);
            return SmileResult.sucess("获取下载链接成功",smilePhotoDownloadVOS );
        } catch (ClientException e) {
            return SmileResult.error("获取下载链接失败");
        }

    }


    @Override
    @Transactional
    public SmileResult updataRecordPay(ShootRecordSearchParament shootRecordSearchParament) {
        Long shootRecordId = shootRecordSearchParament.getShootRecordId();
        Boolean pay = shootRecordSearchParament.getPay();
        if (pay){
            //更新订单数据数据
            SmileShootRecord shootRecord = recordService.getById(shootRecordId);
            shootRecord.setPay(true);
            shootRecord.setRecordOrderNo("SP-"+shootRecord.getId());
            shootRecord.setPayedAmount(shootRecord.getAmount());
            shootRecord.setPhotographerId(shootRecordSearchParament.getPhotographerId());
            recordService.updateById(shootRecord);

            //结算摄影师的分成金额
            Long photographerId = shootRecord.getPhotographerId();
            LambdaQueryWrapper<SmilePhotographerDividend> queryWrapper=new LambdaQueryWrapper();
            queryWrapper.eq(SmilePhotographerDividend::getPhotographerId,photographerId);
            queryWrapper.eq(SmilePhotographerDividend::getPhotographerDividendType,DividendTypeEnum.SHOOT_DIVIDEND);
            queryWrapper.eq(SmilePhotographerDividend::getPhotographerDividendProportionLock,true);
            List<SmilePhotographerDividend> shootDividendList = dividendService.list(queryWrapper);



            BigDecimal photographerDividendProportion;
            //总金额
            BigDecimal amount=shootRecord.getAmount();
            //分红账单
            SmilePhotographerDividendBill smileShootDividendBill = new SmilePhotographerDividendBill();
            smileShootDividendBill.setAmount(amount);
            smileShootDividendBill.setPhotographerDividendType(DividendTypeEnum.SHOOT_DIVIDEND.getName());
            smileShootDividendBill.setShootRecordId(shootRecordId);
            smileShootDividendBill.setPhotographerId(photographerId);
            if (ObjectUtils.isListSole(shootDividendList)) {

                SmilePhotographerDividend photographerDividend = shootDividendList.get(0);
                //摄影师分层比例
                photographerDividendProportion= photographerDividend.getPhotographerDividendProportion();
                //分成金额
                smileShootDividendBill.setPhotographerDividendId(photographerDividend.getId());

            }else {
                ShootRecordSearchParament   amountSearchParament =new ShootRecordSearchParament();
                amountSearchParament.setPhotographerId(photographerId);
                BigDecimal allAmount = recordService.getRecordAmout(amountSearchParament);
                SmilePhotographerDividendRule rule = dividendRuleService.getShootRule(allAmount);
                photographerDividendProportion = rule.getPhotographerDividendProportion();
            }
            BigDecimal photographerDividendAmount=amount.multiply(photographerDividendProportion).multiply(BigDecimal.valueOf(0.01));
            smileShootDividendBill.setPhotographerDividendAmount(photographerDividendAmount);
            dividendBillService.save(smileShootDividendBill);

            //佣金分红账单
            SmilePhotographer referralPhotographer = photographerService.getPhotographerByReferredPhotographerId(photographerId);
            if (!ObjectUtils.isEmpty(referralPhotographer)){
                SmilePhotographerDividendBill smileCommissionDividendBill = new SmilePhotographerDividendBill();
                smileCommissionDividendBill.setAmount(amount);
                smileCommissionDividendBill.setShootRecordId(shootRecordId);
                smileCommissionDividendBill.setPhotographerDividendType(DividendTypeEnum.COMMISSION_DIVIDEND.getName());
                smileCommissionDividendBill.setPhotographerId(referralPhotographer.getId());
                SmilePhotographerDividendRule commissionRule = dividendRuleService.getCommissionRule();
                BigDecimal commissionDividendAmount=amount.multiply(commissionRule.getPhotographerDividendProportion()).multiply(BigDecimal.valueOf(0.01));
                smileCommissionDividendBill.setPhotographerDividendAmount(commissionDividendAmount);
                dividendBillService.save(smileCommissionDividendBill);
            }


            //优惠券更改使用状态
            if (shootRecordSearchParament.getFavorable()) {
                String couponNo = shootRecordSearchParament.getCouponNo();
                if (!ObjectUtils.isEmpty(couponNo)) {
                    couponService.updCouponStatus(couponNo, CouponStatusEnum.USED.getName());
                }
            }


            //更新相册数据
            LambdaUpdateWrapper<SmileAlbumPhoto> updateWrapper=new LambdaUpdateWrapper<>();
            updateWrapper.eq(SmileAlbumPhoto::getShootRecordId,shootRecord.getId());
            updateWrapper.set(SmileAlbumPhoto::getDownloadLock,true);
            albumPhotoService.update(updateWrapper);


            //积分获取
            List<Long> photoIds = shootRecordSearchParament.getPhotoIds();
            earnPointsSubService.downloadPhotoPoints(shootRecord.getClientId(),shootRecord.getClientNo(),photoIds.size());

            return SmileResult.sucess("解锁成功");
        }

        return SmileResult.sucess("解锁失败");
    }






}
